package net.oktaeder.office.simulation;

import java.util.ArrayList;
import java.util.Iterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.oktaeder.office.MainApplication;
import net.oktaeder.office.model.WorkOrder;

/**
 * Main class for simulation and the entry point into simulation sub-system
 * 
 * @author tuukka
 *
 */
public class Simulation {

	private static Simulation instance;
	private static Log log = LogFactory.getLog(Simulation.class);
	private ArrayList<WorkOrder> orders;
		
	private Simulation() {
		orders = new ArrayList<WorkOrder>();
	}
	
	public synchronized static Simulation getInstance() {
		try {
			if (instance == null) {
				instance = new Simulation();
			}
			return instance;
		} catch (Exception ex) {
			log.error("Failed to get instance of Simulation", ex);
			return null;
		}
	}
	
	public void receiveSystemMail(WorkOrder order) {
		log.info("Mail received");
		this.orders.add(order);
	}
	
	public void handleSystemMails() {
		//TODO: implement properly
		Iterator ordersIterator;
		WorkOrder order;
		
		ordersIterator = orders.iterator();
		
		while (ordersIterator.hasNext()) {
			//TODO: see if you can get rid of the type cast
			order = (WorkOrder)ordersIterator.next();
			if (order.getValue("action").equals("quit")) {
				log.info("Quit message received, signaling shutdown");
				MainApplication.getInstance().signalShutDown();
			}
		}
	}
	
	public int amountOfSystemOrders() {
		return orders.size();
	}
	
}
